package com.wxx.aidl

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import com.wxx.service.MyAidl
import com.wxx.service.MyListener
import kotlinx.android.synthetic.main.activity_main.*

/**
 * @author 万祥新
 * 用途:使用Aidl跨进程通讯
 * 实例:在aidlClient app中输入两个数字，然后在adilService app中进行计算并返回给aidlClient app。输入两个数字进行相加
 */
class MainActivity : AppCompatActivity() {
    private var myAidl: MyAidl? = null
    private val connection = object : ServiceConnection{
        override fun onServiceDisconnected(name: ComponentName?) {
            myAidl = null
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            myAidl = MyAidl.Stub.asInterface(service)
            myAidl!!.addListener(object : MyListener.Stub(){
                override fun sum(sum: String?) {
                    txt_result.text = "另一个进程计算出来的结果:$sum"
                }
            })
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        bindService()

        btn_calculate.setOnClickListener {
            if (myAidl == null){
                Toast.makeText(this, "请先启动aidlService app", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val str_num1 = et_num1.text.toString()
            val str_num2 = et_num2.text.toString()
            if (TextUtils.isEmpty(str_num1) || TextUtils.isEmpty(str_num2)) {
                Toast.makeText(this, "请先输入两个数", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            val num1 = str_num1.toFloat()
            val num2 = str_num2.toFloat()

            myAidl?.calculate(num1, num2)
        }
    }

    private fun bindService() {
        val intent = Intent()
        intent.setPackage("com.wxx.service")
        intent.action = "com.wxx.aidl.service"
        bindService(intent, connection, Context.BIND_AUTO_CREATE)
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(connection)
    }

    private fun log(str: String){
        Log.e("wxx", str)
    }
}
